use crate::models::category_paths::{self, CreateParams};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use loco_rs::prelude::*;

pub fn routes() -> Router<AppContext> {
    Router::new()
        .route("/category-paths", post(create))
        .route("/category-paths/:id", get(get_by_id))
        .route("/category-paths/:id/delete", post(delete))
        .route(
            "/category-paths/by-category/:category_id",
            get(get_by_category),
        )
        .route("/category-paths/by-path/:path_id", get(get_by_path))
}

async fn create(
    State(state): State<AppContext>,
    Json(params): Json<CreateParams>,
) -> Result<Response> {
    let category_path = category_paths::Model::create(&state.db, &params).await?;
    format::json(category_path)
}

async fn get_by_id(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let category_path = category_paths::Model::find_by_id(&state.db, &id).await?;
    format::json(category_path)
}

async fn delete(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let category_path = category_paths::Model::find_by_id(&state.db, &id).await?;
    category_path.delete(&state.db).await?;
    format::json(())
}

async fn get_by_category(
    State(state): State<AppContext>,
    axum::extract::Path(category_id): axum::extract::Path<String>,
) -> Result<Response> {
    let paths = category_paths::Model::find_by_category_id(&state.db, &category_id).await?;
    format::json(paths)
}

async fn get_by_path(
    State(state): State<AppContext>,
    axum::extract::Path(path_id): axum::extract::Path<String>,
) -> Result<Response> {
    let paths = category_paths::Model::find_by_path_id(&state.db, &path_id).await?;
    format::json(paths)
}
